// pages/order/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
 tabs: [{
        id: 0,
        name: "全部订单",
        isActive: true
      },
      {
        id: 1,
        name: "待付款",
        isActive: false
      },
      {
        id: 2,
        name: "待发货",
        isActive: false
      },
      {
        id: 3,
        name: "退货/退款",
        isActive: false
      }
    ],

    orders:[],
  },

  changeByIndex(index){
    let tabs = JSON.parse(JSON.stringify(this.data.tabs));
    tabs.forEach((v,i)=>i === index ? v.isActive=true:v.isActive=false);
    this.setData({
      tabs
    })
  },

  handleClick(e){
    // console.log(e);
    const {index} = e.detail;
    this.changeByIndex(index);
    // 重新发送请求，type = 1, index = 0
    this.getOrders(index + 1);
  },



  /**
   * 生命周期函数--监听页面显示
      onShow不同于onLoad，无法在形参上接受options参数
   */
  onShow: function () {
    let currentPages =  getCurrentPages();
    // console.log(currentPages);
    let currentPage = currentPages[currentPages.length - 1];
    // console.log(currentPage.options);
    const {type} = currentPage.options;
    this.changeByIndex(type - 1);
    // console.log(type);
    this.getOrders(type)
  },

    // 获取订单数据
  async getOrders(type){
    const token = wx.getStorageSync('token');
    if(!token){
      // 没有获取授权
      wx.navigateTo({
        url: '/pages/auth/index'
      });
      setTimeout(() => {
        const token = wx.getStorageSync('token');
      }, 500);
      const res = await request({url:"/my/orders/all", data:{type}, header:{Authorization: token}});
      // console.log(res);
    }
    const res = await request({url:"/my/orders/all", data:{type}, header:{Authorization: token}});
    // console.log(res);
    this.setData({
      orders:res.orders.map(v=>({...v, create_time_cn:(new Date(v.create_time * 1000).toLocaleString())}))
    })  
  },




  // backToHome(){
  //   wx.switchTab({
  //     url: '/pages/index/index',
  //   })
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
//  console.log(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  // onShow(options){
  //   console.log(options);
  // },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})